package com.dangdi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.CharBuffer;
import java.util.Arrays;

public class SocketClient2 implements Runnable {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    InputStream inputStream = null;
    OutputStream outputStream = null;
    Socket socket = null;
    private String cpHost = null;
    private int cpPort;
    private boolean serverConnetion = false;

    public boolean isServerConnetion() {
        return serverConnetion;
    }

    public void setServerConnetion(boolean serverConnetion) {
        this.serverConnetion = serverConnetion;
    }

    public SocketClient2(String host, int port) throws IOException {
        logger.info("socket客户端初始化 host=" + host + ",port=" + port);
        socket = new Socket(host, port);
        serverConnetion = true;
        cpHost = host;
        cpPort = port;
        logger.info("初始化成功!");
        inputStream = socket.getInputStream();
        logger.info("inputStream初始化");
        outputStream = socket.getOutputStream();
        logger.info("outputStream初始化");
    }

    /**
     * 数据发送线程
     */
    public void SendThread(String msg) {
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(outputStream));
        pw.write(msg);
        pw.flush();
    }

    public int closeSocketClient() {
        try {
            inputStream.close();
            outputStream.close();
            socket.close();
            logger.info("关闭io流以及socket");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 数据接收线程
     */
    @Override
    public void run() {
        logger.info("线程启动了");
        serverConnetion = true;
        try {
            byte line[] = new byte[1024];      //回复数据长度
            String str = "";
            while (inputStream.read(line) != -1) {
                str = new String(line, "UTF-8").trim();
                System.out.println(str);
//                        System.out.println("client--> " +Arrays.toString(line) );
//                       SocketMessageController.controller(Arrays.toString(line));
//                        System.out.println(str.replace(" ",""));
            }
        } catch (IOException e) {
            serverConnetion = false;
            if (socket.isClosed()) {
                System.out.println("这个客户端挂了");
            } else {
                System.out.println("服务器挂了");
            }
        }
        logger.info("线程结束了");
        serverConnetion = false;
    }
}